/*
require  tabmenu.js
require  datagrid.js
require  core1.1
require  dataColumn.js
require  minChart.js
 */
if (typeof QSAPI == "undefined") {
	var QSAPI = {
		Widget : {}
	};
} else if (!QSAPI.Widget) {
	QSAPI.Widget = {};
}

QSAPI.Widget.MarketIndex=function(container, config, callback, sdkid){
    this.container = null;
    this.id = this.subscribeID = sdkid||new Date().getTime();
    this.profile={
        chartCfg:{days:1},
        chartProfile:{
            lineType: "montain",
            showX: true,
            showY: true
        },
        chartFixed:false,
        chartHeight:180,
        
        hasSetting:false,
        settingPanel:null,
        clickOnSymbol:false,
        hoverChart:false,

        showFirstLabel:false,
        showTimeLabel:false,
        showInterTime:true,
        showInterHour:true,//only show interHour label
        isAPI:true,

        percentage:true,
        isFormat:true,//whether need format
        isUnit:false, //whether need change separate
        fixHeight:true,
        numberSeparate: "",//between number and unit
        gridColumns:["Symbol","Date","Chg","Chg%","LastPrice"],
        colConfig:{"Chg":{"decimal":2}, "Chg%":{"decimal":2}, "LastPrice":{"decimal":2}},
        tabConfig:{},
        
        dataType:"pull",
        clickToggle:false, 
        headerRow: false,
        showTime: false,

        autoSlideToActiveTab:true,
        menuList:["canada","us","ms","asian","european"],
        openedMenu:null,
        showTab:true

    };
    this.referID = {
		PID : {
			field:"secId",
			errorMessage:"No Morningstar ID"
		},
		Valid:{
			field:"valid",
			errorMessage:"No Entitlement"
		},
		GKey: {
			field:"gkey",
			errorMessage:"No Tenfore Info"
		},
		Symbol:{
			field:"symbol"
		}
	};
    this.callback=callback||{};
    this.staticValue={
        padheight:5,
        minWidth:120,
        defaultValue:"--"
    };
    var qslan=QS_Lang.marketindices;
    //default data
    this.menuInfo={
        "canada":{
            txt:qslan["canada"],
            tickers:['0P00001FJG','0P00001G7J', '0P00001G7B', '0P00001GJH', '0P00001GJK','0P00008IVF','0P00008PAC', '0P00001QO6']
        },
        "us":{
            txt: qslan["us"],
            tickers:['0P00001FJG','0P00001G7J', '0P00001G7B', '0P00001GJH', '0P00001GJK']
        },
        "ms":{
            txt: qslan["ms"],
            tickers:['0P00001GJH','0P00001GJI', '0P00001GJJ', '0P00001GJK']
        },
        "asian":{
            txt: qslan["asian"], 
            tickers:['0P00006NNM','0P00006MR4', '0P00001FL8', '0P00001G5J', '0P00001MUH']
        },
        "european":{
            txt: qslan["european"], 
            tickers: ['0P00001IS1','0P00008ICX', '0P00001FKV', '0P00006F1A', '0P00006NOT']
        },
        "northamerican":{
            txt: qslan["northamerican"],
            tickers: ['0P00001FJG','0P00001G7J', '0P00001G7B','0P00008IVF','0P00008PAC', '0P00001QO6']
        }
    };
    this.tickersInfo={
        "canada":{  
            '0P00001GJH':qslan["mtn_mstar_usmarket"],
            '0P00001GJK':qslan["ms"]+" "+qslan["mtn_smallcap"],
            '0P00008IVF':qslan["mtn_sp/tsx"],
            '0P00008PAC':qslan["mtn_sp/tsx60"], 
            '0P00001QO6':qslan["mtn_sp/tsx_venture"], 
            '0P00001FJG':qslan["mtn_djia"],
            '0P00001G7J':qslan["mtn_sp500"],
            '0P00001G7B':qslan["mtn_nasdaq"]
        },"us":{    
            '0P00001FJG':qslan["mtn_djia"],
            '0P00001G7J':qslan["mtn_sp500"],
            '0P00001G7B':qslan["mtn_nasdaq"],
            '0P00001GJH':qslan["mtn_mstar_usmarket"],
            '0P00001GJK':qslan["ms"]+" "+qslan["mtn_smallcap"]
        },"ms":{    
            '0P00001GJH':qslan["mtn_usmarket"],
            '0P00001GJI':qslan["mtn_largecap"], 
            '0P00001GJJ':qslan["mtn_midcap"], 
            '0P00001GJK':qslan["mtn_smallcap"]
        },"asian":{ 
            '0P00006NNM':qslan["mtn_shanghai"],
            '0P00006MR4':qslan["mtn_nikkei"],
            '0P00001FL8':qslan["mtn_hangseng"],
            '0P00001G5J':qslan["mtn_bombay"],
            '0P00001MUH':qslan["mtn_australia"]
        },"european":{
            '0P00001IS1':qslan["mtn_ftse100"],
            '0P00008ICX':qslan["mtn_cac40"],
            '0P00001FKV':qslan["mtn_daxfrank"], 
            '0P00006F1A':qslan["mtn_aex"], 
            '0P00006NOT':qslan["mtn_smi"]
        },"northamerican":{
            '0P00001GJH':qslan["mtn_mstar_usmarket"],
            '0P00001GJK':qslan["ms"]+" "+qslan["mtn_smallcap"],
            '0P00008IVF':qslan["mtn_sp/tsx"],
            '0P00008PAC':qslan["mtn_sp/tsx60"], 
            '0P00001QO6':qslan["mtn_sp/tsx_venture"], 
            '0P00001FJG':qslan["mtn_djia"]
        }
    };
    this.timezone={
        '0P00001FJG':"EST",
        '0P00001G7J':"EST",
        '0P00001G7B':"EST",
        '0P00001GJH':"EST",
        '0P00001GJK':"EST",
        '0P00001GJI':"EST",
        '0P00001GJJ':"EST",
        '0P00001GJK':"EST",
        '0P00006NNM':"CST",
        '0P00006MR4':"JST",
        '0P00001FL8':"CST",
        '0P00001G5J':"IST",
        '0P00001MUH':"EDT",
        '0P00001IS1':"GMT",
        '0P00008ICX':"CET",
        '0P00001FKV':"CET",
        '0P00006F1A':"CET",
        '0P00006NOT':"CET"
    };
    this._textKey = document.body.textContent ? 'textContent' : 'innerText';
    this.lastSubscribeTicker=null;
    this.miniChart=null;
    this.dataGrid = null;
    this.activeRow = null;
    this.container = container;
    this.id = sdkid||new Date().getTime();
    this.loaded=false;
    if(config.menuList&&config.menuList.length>0){
        this.profile.menuList=config.menuList;
    }
    if(config.gridColumns&&config.gridColumns.length>0){
        this.profile.gridColumns=config.gridColumns;
    }
    $.extend(true,this.profile, config);
    var self=this;
    this.dataInterface = {
        getQuoteData:function(geky,field){
            return QSAPI.DataManager._getData(geky,field);
        },
        subscribe:function(tickerObjects){
			var subscribe="subscribePush";
			if(self.profile.dataType=="pull"){
				subscribe ="subscribePull";
			}
			QSAPI.DataManager[subscribe](self,tickerObjects,{
                onFailure:function(result){
                    if(typeof self.callback.processInvalid =="function"){
						self.callback.processInvalid(result);
					}
                }
			});
		},
		unSubscribe:function(tickerObjects){
			var unsubscribe="unSubscribePush";
			if(self.profile.dataType=="pull"){
				unsubscribe = "unSubscribePull";
			}
			QSAPI.DataManager[unsubscribe](self,tickerObjects);
		}
    };
};
QSAPI.Widget.MarketIndex.prototype = {
    init: function(){
        this._createDom();
        this._initMenu();
        this.scrollPanel = new Util.ScrollPanel(this.el.find(".grid"),{showX:false,delayRun:false,showY:this.profile.fixHeight});
        if(this.profile.hasSetting){
            this._createSettingPanel();
        }
    },
    _checkTicker : function(tickerList, needCheckIDs,needID,callback) {//for sdk
		var ids = [], invalid = {},isValid=true,symbol=null,tempID = null,needCheck=null,validTickerObject=[];
		for ( var i = 0, l = tickerList.length; i < l; i++) {
			tempID = null;
			isValid=true;
			for(var j=0,m=needCheckIDs.length;j<m;j++){
				needCheck = needCheckIDs[j];
				tempID = tickerList[i]["getField"](needCheck.field);
				if(typeof tempID=="undefined"||tempID==''||!tempID){//false
					if(!invalid[needCheck["errorMessage"]]){
						invalid[needCheck["errorMessage"]]=[];
					}
					invalid[needCheck["errorMessage"]].push(tickerList[i]);
					isValid=false;
					break;
				}
			}
			if(isValid){
				ids.push(tickerList[i]["getField"](needID.field)||symbol);
				validTickerObject.push(tickerList[i]);
			}
		}
		callback(ids,validTickerObject,invalid);
	},
    setData:function(data){//{}
        //{id:{txt:"",tickers:{"ticker":name}}}
        for(var menu in data){
            var tickers=[],tickerinfo={};
            if(data[menu]["ticker"]){
                for(var ticker in data[menu]["ticker"]){
                    tickers.push(ticker);
                    if(data[menu]["ticker"][ticker]){
                        tickerinfo[ticker]=data[menu]["ticker"][ticker];
                    }
                }
            }
            if(!this.menuInfo[menu]){
                this.menuInfo[menu]={txt:menuNames[menu]["txt"]||menu,tickers:tickers};
                var tickersName={};
                tickersName[menu] = tickerinfo;
                this.setTickersName(tickersName);
            }else{
                if(data[menu]["txt"]){
                    this.menuInfo[menu]["txt"]=menuNames[menu]["txt"];
                }
                if(tickers.length>0){
                    var existsTickers={};
                    existsTickers[menu]=tickers;
                    this.setTickers(existsTickers);
                }
                if(tickerinfo){
                    var existsTickerName={};
                    existsTickerName[menu]=tickerinfo;
                    this.setTickersName(existsTickerName);
                }
            }
        }
    },
    setTickers:function(menuTickers){
        for(var menu in menuTickers){
            if(!this.menuInfo[menu]){
                this.menuInfo[menu]={txt:menu,tickers:menuTickers[menu]};
            }else{
                this.menuInfo[menu]["tickers"]=menuTickers[menu];
            }
        }
    },
    setMenusName:function(menuNames){
        for(var menu in menuNames){
            if(!this.menuInfo[menu]){
                this.menuInfo[menu]={txt:menuNames[menu],tickers:[]};
            }else{
                this.menuInfo[menu]["txt"]=menuNames[menu];
            }
        }
    },
    setTickersName:function(tickerNames){//{"us:{"0P0123404":"tickername"}}
       $.extend(true,this.tickersInfo,tickerNames);
    },
    setTimeZones:function(timezone){
        $.extend(true,this.timezone,timezone);
    },
    setLoadingHandle:function(showHandle,hiddenHandle){
    	var self=this;
        if(typeof showHandle=="function"){
            this.showLoading=function(){
            	showHandle.apply(self);
            };
        }
        if(typeof hidden=="function"){
            this.hideLoading=function(){
            	hiddenHandle.apply(self);
            };
        }
    },
    _createDom:function(){
        var html='<div class="qs-marketindex">'+
                    '<div class="tabmenu"></div>'+
                    '<div class="grid"></div>'+
                    '<div class="minichart" style="visibility:hidden;"></div>'+
                '</div>';
        this.el = $(html);
        this.el.appendTo(this.container);
        if(this.profile.width){
            this.el.css({
                width: this.profile.width
            });
        }else if(this.profile.initwidth){
            this.el.css({
                width: this.profile.initwidth
            });
        }
        if(this.profile.fixHeight&&this.profile.initheight){
            this.el.css({
                height: this.profile.initheight
            });
        }
        if(this.profile.width<300){//if the width is too narrow, will add special class
            this.el.find(".tabmenu").addClass("homepage");
        }
        if(this.profile.showTime){
            var legend = "<div class='rtc-legend-txt' style='height: 17px;line-height: 17px;font-size: 10px; color: hsl(0, 0%, 39%); padding: 0 3px;'><span class='ticker'></span>&nbsp;&nbsp;<span class='time'></span></div>";
            var gridTitleHTML = '<div class="title"><h3>Real Time Updates</h3></div>';
            this.el.find(".minichart").prepend(legend);    
            if(this.profile.chartFixed){
                this.el.find(".minichart").after(gridTitleHTML);   
            }else{
                this.el.find(".tabmenu").after(gridTitleHTML); 
            }
        }
    },
    menuOnActive:function(menuId){
        if(this.currentTabMenuId != menuId){
        	if(typeof this.currentTabMenuId!='undefined'){//unsubscribe
        		this.dataInterface.unSubscribe(this.cacheValidTicker[this.currentTabMenuId]["tickerList"]);
        	}
            this.currentTabMenuId = menuId;
            this._stateChangeHandler("openedMenu",menuId);
            this.activeRow = null;
            if (!this.dataGrid) {
                this._initGrid();
            }else if(!this.profile.chartFixed){
                this.el.find(".minichart").css({"visibility":"hidden"}).appendTo(this.el);
            }
            this._reBuildGridData(menuId);
        }
    },
    _initMenu: function(){
    	if(this.profile.showTab){
	        var self = this;
	        var cb = {
	            onActive: function(tab){
	                self.menuOnActive(tab.id);
	            }
	        };
	        this.tabMenu = new Util.TabMenu(this.el.find(".tabmenu"), this.getMenuData(), cb, {
	            autoResize:true,
	            tabsList: false,
	            vertical: false,
	            activeTabId: this.profile.openedMenu,
	            autoSlideToActiveTab:this.profile.autoSlideToActiveTab,
	            needTitle:true 
	        });
    	}else{
    		this.menuOnActive(this.profile.openedMenu);
    	}
    },
    _getCols:function(){
        var lan=QS_Lang.marketindices,cols=[{header: 'id',dataIndex: 'id',dataType: 'string',hide: true}];
        this.columnMap = {
            "UpDown": {header: '<span style="display:none;">Up/Down</span>',dataIndex: 'UpDown',className: 'column-updown',align: 'center', per:5},
            "Symbol":{header: '',dataIndex: 'Symbol',dataType: 'string', per:28, className: 'symbol-name',ellipsis:true},//added by wind @ 20120326 
            "Date":{header: lan["mk_coldate"],dataIndex: 'Date',align: 'right',dataType: 'Date',dataFormat: 'yyyy-M-d',className: 'bold-cell',per:18},
            "LastPrice":{header: lan["mk_collast"],dataIndex: 'LastPrice',align: 'right',dataType: 'float',per:18}, 
            "Chg":{header: lan["mk_colchg"],dataIndex: 'Chg',align: 'right',dataType: 'float',className: 'bold-cell',per:16}, 
            "Chg%":{header: lan["mk_colchgp"],dataIndex: 'Chg%',align: 'right',dataType: 'float',className: 'bold-cell',per:15}
        };
        $.extend(true,this.columnMap,this.profile.colConfig);
        if(this.profile.gridColumns.length>0){
            var columns=this.profile.gridColumns,perSum=0;
            for(var i=0,l=columns.length;i<l;i++){
                if(this.columnMap[columns[i]]){
                    perSum += this.columnMap[columns[i]]["per"];
                    cols.push(this.columnMap[columns[i]]);
                }
            }
            for (var i=0,l=cols.length;i<l;i++) {
                if(typeof cols[i]["per"]!='undefined'){
                    cols[i]["width"] = cols[i]["per"] / perSum * 100 + "%";
                }
            }
        }else{
            var tempcol=null;
            for(var dataindex in this.columnMap){
                tempcol= this.columnMap[dataindex];
                tempcol["width"] =tempcol["per"]+ "%";
                cols.push(tempcol);
            }
        }
        return cols;
    },
    _removeLabelTime:function(timeStr){
        //"09:30 AM"->"09:30";
        return $.trim(timeStr).replace(/\s*(PM|AM|a.m.|p.m.)/ig,"");
    },
    _trim:function(timeStr){
        return $.trim(timeStr).replace(/\s/ig,"");
    },
    _isIntNum:function(timeStr){
        return timeStr.indexOf(":00")>0;
    },
    _getPureIntPart:function(timeStr){
        //"09:30 AM"-> 9
        return parseInt(timeStr.replace(/:\d*\s*\w*/ig,"").replace(/^0*/g,""));
    },
    _getIntPart:function(timeStr){
        //"09:30 AM"->"9AM";
        return timeStr.replace(/^0*/g,"").replace(/:(\d*\s*)/ig,"");
    },
    _convertTF:function(timeStr){
        //"9:30 PM"-> 21:30
        var pre=/pm/ig.test(timeStr)?12:0,returnValue=this._getPureIntPart(timeStr);
        var hour = returnValue>=12?returnValue:pre+returnValue;
        returnValue = timeStr.replace(/\d+(?=:)/ig,hour);
        return this._removeLabelTime(returnValue);
    },
    _processData:function(t){
        var isInt=false;
        for(var i=t.length-1;i>=0;i--){
            isInt=false;
            if(t[i][1]==null||typeof t[i][1] == "number"||typeof t[i][1]=='undefined'){
                t.splice(i,1);
                continue;
            }
            if(this._isIntNum(t[i][1])) {//is inter time
                isInt=true;
            }

            if(this.profile.showInterHour&&!isInt){//remove un inter time
                t.splice(i,1);
            }else{
                if(this.profile.showFirstLabel&&i==0){
                    t[i][1]=this._trim(t[i][1]);
                    continue;
                }
                if(!this.profile.showTimeLabel){//don't display AM/a.m.
                    t[i][1]=this._convertTF(t[i][1]);
                }else if(this.profile.showInterTime){//display 9AM/9a.m.
                    t[i][1]=this._getIntPart(t[i][1]);
                }
            }
        }
    },
    onStartDraw:function(data){
        if(this.profile.chartCfg.days==1){
            var t=[];
            if(data[0].price){
                this._processData(data[0].price.xAxis);
            }
        }
    },
    _expanseChart:function(tickerObject,row){
        var self=this;
        if(!this.activeRow){
            this.activeRow=row;
            this._activeRow(row,true,function(){self._animateComplete();});
        }else{
            if(this.activeRow==row){
                if(!this.profile.clickToggle) return;
                this.activeRow=null;
                this._activeRow(row,false);
            }else{
                this._activeRow(this.activeRow,false);
                this._expanseRow(this.activeRow.el,false);
                this.activeRow=row;
                this._activeRow(row,true);
            }
        }
        if(!this.activeRow){//unactive
            this.el.find(".minichart").hide();
            this._expanseRow(row.el,false,function(){self._animateComplete();});
            row.el.removeClass("rtq-grid-row-selected");
        }else{
            this._expanseRow(this.activeRow.el,true,function(){self._animateComplete();});
            this.el.find(".minichart").show();
            this.el.find(".minichart").css("visibility","hidden");
            this._drawMinChart(row, tickerObject);
            var legend = this.el.find('.rtc-legend-txt .ticker');
            if (legend.length > 0) {
                var name = row.cells.Symbol.text;
                legend.html(name);
            }
        }
        /*
        if(typeof self.callback.onCellClick=='function'){
                    self.callback.onCellClick(e,cell,row);
                }*/
    },
    _initGrid: function(){
        var self = this;
        var cb = {
            onRowSelected: function(e, row){
                var tickerObject = self._getTickerObjectByGkey(row.id);
                if(!self.profile.hoverChart){
                    self._expanseChart(tickerObject,row);
                }
                if(!self.profile.clickOnSymbol&&self.callback.onClick){
                    if($(e.target).hasClass("rtq-grid-cell-ctn")){//click row
                        self.callback.onClick({
                            ticker:tickerObject,
                            component:'marketIndex'
                        });
                    }
                }
            }
        };
        if(this.profile.hoverChart){
            cb.onRowMouseover=function(e,row){
                Util.DelayRun('mouseoverRow.marketIndex', function(){
                    var tickerObject = self._getTickerObjectByGkey(row.id);
                    self._expanseChart(tickerObject,row);
                },500,self);
            };
        }
        if(this.profile.clickOnSymbol){
            cb.onCellClick=function(e,cell,row){
                if(self.callback.onClick&&cell.key=="Symbol"){
                    var tickerObject = self._getTickerObjectByGkey(row.id);
                    self.callback.onClick({
                        ticker:tickerObject,
                        component:'marketIndex'
                    });
                }
            }
        }
        this.dataGrid = new Util.DataGrid(this.el.find(".grid"), [], {
            column: this._getCols(),
            autoWidth: true,
            autoHeight: true,
            rowInvertSelect:false,
            headerRow: this.profile.headerRow,
            htmlLayer: 'div',
            rowDragDropGroup: 'GRID1'
        }, cb);
        if(this.profile.headerRow){
            this.el.find(".grid .rtq-grid-hd").css({"display":"block"});
        }
    },
    _createSettingPanel: function(){
        var  self = this,qslang=QS_Lang.marketindices;
        var settingPN = this.profile.isAPI?this.profile.settingPanel||$("body"):this.__winObj.settingPanelObj.settingPN;
        settingPN.addClass('rtq-window-setpn-mki');
        var settingPNGroupBox = new Util.GroupBox(settingPN.find(".wrap")||settingPN, [{
            name: qslang["mk_gdisplay"],
            id: 1
        }], {
            width: 177,
            groupBoxHeight: 150
        });     
        settingPNGroupBox.getGroup(1).bd.html('<h5>'+qslang["mk_gchartscope"]+'</h5>');
        
        new Util.DropDownList(settingPNGroupBox.getGroup(1).bd, function(t, v){
                self.profile.chartRange = v;
                self.changeChartRange(v);
            }, this.getChartRangeData(),
            {width: 163, className:"rtq-ddl-black"}
         );
    },
    getMenuData:function(){
        var menu=[],menulist=this.profile.menuList;
        for(var i=0,l=menulist.length;i<l;i++){
            if(this.menuInfo[menulist[i]]){
                menu.push({id:menulist[i],txt:this.menuInfo[menulist[i]].txt,closable:false});
            }
        }
        return menu;
    },
    getChartRangeData:function(){
        var qslang=QS_Lang.marketindices;
        return [{txt: '1 '+qslang["mk_gchart_day"],val: '1d' }, 
                {txt: '5 '+qslang["mk_gchart_days"],val: '5d' },
                {txt: '1 '+qslang["mk_gchart_month"],val: '1m'}, 
                {txt: '3 '+qslang["mk_gchart_months"],val: '3m'}, 
                {txt: '6 '+qslang["mk_gchart_months"],val: '6m'}, 
                {txt: '1 '+qslang["mk_gchart_year"],val: '1y'}, 
                {txt: '2 '+qslang["mk_gchart_years"],val: '2y'}];
    },
    _activeRow:function(row,bool){
        var symbolEl=row.cells["Symbol"].el;
        var symbolContentEl=symbolEl.find('.rtq-grid-cell-ctn');
        var lastPriceEl=row.cells["LastPrice"].el;   
        if(!bool){
            symbolEl.css({"font-weight":"normal"});
            lastPriceEl.css({"font-weight":"normal"});
        }else{
            symbolEl.css({"font-weight":"bold"});
            lastPriceEl.css({"font-weight":"bold"});
        }
        this.rowHeight=symbolContentEl.height();
    },
    _animateComplete:function(){
        if(this.profile.isAPI){
            this.changeOutSize(this.profile.width||this.el.width(),this.profile.height||this.el.height());
        }else{
            this.changeOutSize();
        }
    },
    _pp0:function (n){
        if (n < 10) 
            n = '0' + n;
        return n;
    },
    _getLastTimefromData:function(d){
        var l = d.length-1,tick=0,time="";
        for(var i=l;i>=0;i--){
            if(!isNaN(d[i][1])){
                tick = d[i][d[i].length-1];
                break;
            }
        }
        if(tick>0){
            var dt = new Date(tick);
            time = this._pp0(dt.getHours())+":"+this._pp0(dt.getMinutes());
        }
        return time;
    },
    _expanseRow:function(row,bool,completeFunction){
        if(!this.profile.chartFixed){
            var self=this;
            row.animate({height: (bool?(self.profile.chartHeight+self.rowHeight+this.staticValue.padheight):self.rowHeight+this.staticValue.padheight)+'px'}, {
                duration: "normal",
                complete: function(){
                    if(completeFunction){completeFunction();}
                }
            });
        }
    },
    _subscribeTickerForChart: function(tickerObject){
        var self = this;
        if(typeof this.showLoading =='function'){
            this.showLoading();
        }
        self.lastSubscribeTicker = tickerObject;
        self.miniChart.subscribe(tickerObject,self.profile.chartCfg);
    },
    _getTickerName:function(menu,ticker){
    	var symbol= ticker["getField"](this.referID["Symbol"].field);
        var name= this.tickersInfo[menu][symbol];
        if(!name){
            var temp = this.dataInterface.getQuoteData(ticker["getField"](this.referID["GKey"].field),"Name");
        }
    	return name||(temp&&temp.value?temp.value:symbol);
    },
    _drawMinChart:function(row, tickerObject){
        if(!this.profile.chartFixed)
            row.el.append(this.el.find(".minichart").css({"visibility":"hidden"}));  // hide the old chart
        if(!this.miniChart){
            this._initMinChart();
        }else{
            this.miniChart.unSubscribe(this.lastSubscribeTicker);
        }
        if(this.profile.tabConfig[this.currentTabMenuId]&&typeof this.profile.tabConfig[this.currentTabMenuId].decimal!='undefined'){
            this.miniChart.setPercision(this.profile.tabConfig[this.currentTabMenuId].decimal);
        }
        this._subscribeTickerForChart(tickerObject);
    },
    _initMinChart: function(){
    	var self=this;
        this.miniChart = new QSAPI.Widget.MiniChart(this.el.find(".minichart"), $.extend(this.profile.chartProfile , {
            width: this.profile.width,
            height: this.profile.chartHeight
        }),{
        	drawStart:function(data){
        		self.onStartDraw(data);
        	},
        	drawEnd:function(data){
                if(self.activeRow){
                    self.el.find(".minichart").css({"visibility":"visible","marginTop":(self.rowHeight)});
                }
                if(self.profile.showTime){
                    var time = self._getLastTimefromData(data[0].price.data);
                    var timezone = "";
                    if(self.activeRow){
                        var tid = self.lastSubscribeTicker["getField"](self.referID["Symbol"].field);
                        if(self.timezone&&self.timezone[tid]){
                            timezone =self.timezone[tid];
                        }
                    }
                    self.el.find('.rtc-legend-txt .time').html(time+" "+timezone);
                }
                if(typeof self.hideLoading=='function'){
                    self.hideLoading();
                }
        	}
        },this.id);
        this._setChartDataManager();
    },
    _setChartDataManager:function(){
        QSAPI.DataManager.Chart.dataSourceType=this.profile.dataType;
        QSAPI.DataManager.Chart.dataDomain=typeof QSAPI.getQSPath=='function'?QSAPI.getQSPath():"./";
        QSAPI.DataManager.Chart.crossDomain = true;
    },
    _reBuildGridData: function(menuId){
        var self = this;
        if(!this.cacheValidTicker){this.cacheValidTicker={};}
        if(!this.cacheValidTicker[menuId]){this.cacheValidTicker[menuId]={};}
        var data=[];
        if (!this.cacheValidTicker[menuId]["tickerList"]||this.cacheValidTicker[menuId]["tickerList"].length == 0) {
            var allTickerList = this.menuInfo[menuId].tickers;
            if(typeof allTickerList[0]=="string"){
            	allTickerList = QSAPI.TickerFactory.create(allTickerList);
            }
            if(typeof this.showLoading =='function'){
                this.showLoading();
            } 
            allTickerList.ready(function(tickerList){
            	if(typeof self.hideLoading=='function'){
                    self.hideLoading();
                }
            	self._checkTicker(tickerList, [self.referID["Valid"],self.referID["GKey"]],self.referID["GKey"],function(gkeylist,tickerObjects,invalidTickers){
					if (self.callback.processInvalid == "function"&&!$.isEmptyObject(invalidTickers)) {
						self.callback.processInvalid(invalidTickers);
					}
                    self.cacheValidTicker[menuId]["tickerList"]=tickerObjects;
                    self.cacheValidTicker[menuId]["gkeyList"]=gkeylist;
                    self.cacheValidTicker[menuId]["gkeyMap"]={};
                    for(var i=0,l=gkeylist.length;i<l;i++){
                        self.cacheValidTicker[menuId]["gkeyMap"][gkeylist[i]]=true;
                    }
                    data = self._fillDList(gkeylist,tickerObjects);
                    self.dataGrid.reBindData(data);
                    self.dataInterface.subscribe(tickerObjects);
                    if(data.length>0){
                        Util.DelayRun('selectRow.marketIndex', function(){
                            self._expanseChart(tickerObjects[0],self.dataGrid.rows[gkeylist[0]]);
                        }, 0, this);
                    }else{
                        self._animateComplete();
                    }
				});
            });
        }
        else {
        	var gkeylist=this.cacheValidTicker[menuId]["gkeyList"];
    		var tickerObjects=this.cacheValidTicker[menuId]["tickerList"];
    		data = this._fillDList(gkeylist,tickerObjects);
            this.dataGrid.reBindData(data);
            //this._forceUpdate();//if don't unsubscribe ,when active again,it will forceUpdate
            self.dataInterface.subscribe(tickerObjects);
            if(data.length>0){
                Util.DelayRun('selectRow.marketIndex', function(){
                    self._expanseChart(tickerObjects[0],self.dataGrid.rows[gkeylist[0]]);
                }, 0, this);
            }else{
                this._animateComplete();
            }
        }
        Util.DelayRun('lastRow.marketIndex', function(){
            self.dataGrid.el.find('.rtq-grid-row:last-child').addClass('last-row');
        },500,this);//added by wind @ 20120326, for quest public site
    },
    _forceUpdate:function(){
    	if(this.cacheValidTicker&&this.cacheValidTicker[menuId]){
    		var gKeyList=this.cacheValidTicker[menuId]["gkeyList"];
    		var tickerObjects=this.cacheValidTicker[menuId]["tickerList"];
	    	for (var i = 0; i < gKeyList.length; i++) {
	            self._forceUpdateData(gKeyList[i],tickerObjects[i]);
	        }
    	}
    },
    _forceUpdateData: function(gkey,tickerObject){
        var aData = {};
        var cols = this.dataGrid.getColumnCfg(), field=null,datalist=null;
        for (var c in cols) {
            field = cols[c].dataIndex;
            if(field=="id") continue;
            if (field == "Up/Down") 
                field = "Chg";
            datalist=this.dataInterface.getQuoteData(gkey, field);
            aData[field] = {
                dataType: cols[c].dataType,
                value: datalist?datalist.value|1:'1'
            };
        }
        this.updateData(tickerObject, aData, false);
    },
    _fillDList: function(gkeyList,tickerObjects){
        var data = [];
        for (var i = 0; i < gkeyList.length; i++) {
            var d = {};
            d["id"] = gkeyList[i];
            d["Symbol"] = this._getTickerName(this.currentTabMenuId, tickerObjects[i]);
            data.push(d);
        }
        return data;
    },
    fileMenuCallback: function(v){//for terminal
        if (v == "refresh") {
            
        }
    },
    saveConfig:function(){
    	return {
    		openedMenu: this.currentTabMenuId,
    		chartCfg: this.profile.chartCfg
    	};
    },
    
    clear:function(){
        for (var p in this) {
            if (!p || p == 'clear') {
                continue;
            }
            this[p] = null;
            delete this[p];
        }
    },
    _stateChangeHandler:function(configName,value){
		if (typeof this.callback.onStateChange == 'function') {
			this.callback.onStateChange(configName,value);
		}
	},
    changeOutSize: function(w,h){
        //alert("change size"+w+":"+h);
        if(this.profile.isAPI){
            w = this.profile.width||w||this.container.width();
            h = this.profile.height||h||this.container.height();
            this.el.css({
                width: w,
                height:h
            });
        }else{
            //if it is terminal, the height of win-bd is static
            w = w||this.container.parent().width();
            h = h||this.container.parent().height();
            this.el.css({
                width: "auto"
            });
            if(this.profile.width>=300){
                this.el.find(".tabmenu").removeClass("homepage");
            }
        }
        if (w < this.staticValue.minWidth) {
            w = this.staticValue.minWidth;
        }
        //this.dataGrid.resize(w,null);
        if(this.activeRow&&!this.profile.chartFixed){
            var symbolEl=this.activeRow.cells["Symbol"].el.find('.rtq-grid-cell-ctn');
            this.rowHeight=symbolEl.height();
            this.activeRow.el.css({height:this.profile.chartHeight+this.rowHeight+this.staticValue.padheight});
        }
        var self=this;
        if (this.profile.fixHeight) {
            var tabHeight=this.el.find(".tabmenu .rtq-tab-wrap").height(),titleHeight=this.el.find(".title").height()||0;
            Util.DelayRun('changeOutSize.marketindex', function(){
                self.scrollPanel.reSize(w, h-tabHeight);
                if (self.scrollPanel.scrollbarY.isShow) {
                    w = w - 13;
                }
                self.dataGrid.resize(w,null);
                self._changeMinChartSize(w, self.profile.chartHeight);
            }, 200, self);
        }
        else {
            this.scrollPanel.reSize(w,null);
            this.dataGrid.resize(w,null);
            h = this.el.height();
        }
        this._heightChangeHandler(h);
    },
    _changeMinChartSize:function(w,h){  // cal miniChart Size.
        if(!this.activeRow) return;
        this.el.find(".miniChart").css({width:w,height:h});
        if (this.miniChart) {
            this.miniChart.changeOutSize(w, h);
        }
    },
    updateData: function(tickerObject, aData, needFlash){
    	var gKey=tickerObject["getField"](this.referID.GKey.field);
        if (this.cacheValidTicker[this.currentTabMenuId]["gkeyList"]&&this.cacheValidTicker[this.currentTabMenuId]["gkeyMap"][gKey]) {
            var _flashMethod = needFlash === false ? (function(){}) : Util.flash,decimal=2,nubtag=false;
            if(this.profile.tabConfig[this.currentTabMenuId]&&typeof this.profile.tabConfig[this.currentTabMenuId].decimal!="undefined"){
                decimal=this.profile.tabConfig[this.currentTabMenuId].decimal;
            }
            var type=null,data=null,orginData=null,el=null,colConfig,oldData,gValue,securitytype=null,datalist=null;
            for (var field in aData) {
                type = aData[field].dataType;gValue = aData[field].value;
                oldData = aData[field].oValue;data = gValue;el = this.dataGrid.DOMMap[gKey][field];
                colConfig=this.columnMap[field];
                if(field == 'Symbol'||!el)  continue;
                securitytype = tickerObject["getField"]("type");
                switch (field) {
                    case 'LastPrice':
                        typeof(el) == "undefined" ? null:_flashMethod(el, data, oldData);
                        break;
                    case "Date":
                       datalist = this.dataInterface.getQuoteData(gKey, "TradeDate");
                       data =  datalist?datalist.value||"":"";
                       break;
                    case 'Chg':
                    case 'Chg%':
                        if (needFlash !== false && typeof(el) != "undefined") {
                            Util.flashWithDirectional(el, data, oldData, data >= 0);
                        }else if(typeof(el) != "undefined"){
                            el.style.color = (data >= 0 ? QS_Style.greenFontColor : QS_Style.redFontColor);
                        }
                        if (field == "Chg") { // update the up/down column;
                            var upd = data;
                            if (upd == 0 || typeof upd == 'undefined') {
                                upd = '';
                            }else {
                                var cls = upd > 0 ? "up" : "down";
                                upd = '<a class="updown ' + cls + '" href="javascript:void(0)">' + cls + '</a>';
                            }
                            var upEl = this.dataGrid.DOMMap[gKey]["UpDown"];
                            if (upEl) 
                                upEl.innerHTML = upd;
                        }
                        break;
                    default:
                        break;
                }
                nubtag=(colConfig&&colConfig["dataType"]=="float")?true:false;
                orginData = data;
                if(nubtag){
                    if(!isNaN(data)){
                        if(colConfig&&typeof colConfig.decimal!='undefined'){
                            decimal =colConfig.decimal;
                        }
                        data = Util.formatDoubledata(data,securitytype,decimal,this.profile.isFormat,this.profile.isUnit,this.profile.numberSeparate,true,false);
                        if(field == 'Chg%'&&/^[-\+]?\d+(\.\d+)?$/.exec(data) && this.profile.percentage){
                        	data = data + "%";
                        }
                    }else{
                         data=this.staticValue.defaultValue;
                    }
                }else if(colConfig&&colConfig["renderer"]){
                	if(field=="Date"){
                        var d=data.split('-');
                        data = colConfig["renderer"](new Date(parseInt(d[0],10),parseInt(d[1],10)-1,parseInt(d[2],10)));
                	}else{
                		data = colConfig["renderer"](data);
                	}
                }
                this.dataGrid.rows[gKey].cells[field].updateCell(data,orginData);     
            }
        }
    },
    _heightChangeHandler:function(height){
        if (!this.loaded) {
            this.lastCallbackHeight = height;
            if (typeof this.callback.onLoad == 'function') {
                this.loaded = true;
                this.callback.onLoad({
                    component: 'marketIndex',
                    height: height,
                    minWidth:this.staticValue.minWidth
                });
            }
        }else {
            if (this.lastCallbackHeight != height) {
                this.lastCallbackHeight = height;
                if (typeof this.callback.onHeightChange == 'function') {
                    this.callback.onHeightChange({
                        height: this.lastCallbackHeight,
                        component: 'marketIndex'
                    });
                }
            }
        }
    },
    _getTickerObjectByGkey:function(gkey){
    	var gkeyList=this.cacheValidTicker[this.currentTabMenuId]["gkeyList"];
		var tickerObjects=this.cacheValidTicker[this.currentTabMenuId]["tickerList"];
    	for(var i=0,l=gkeyList.length;i<l;i++){
    		if(gkey==gkeyList[i]){
    			return tickerObjects[i];
    		}
    	}
    	return null;
    },
    changeChartRange:function(r){
        var self=this;
        var l = r.length - 1, step = parseInt(r.substr(0,l));
        var today = new Date(), todayIdx = RTQ_ChartUtil.toDateIndex(today);
        var cfg = {"endIndex":todayIdx}; 
        switch (r.charAt(l)) {
            case "d":
                cfg["freq"] = 1;
                cfg["startIndex"] = todayIdx - (step - 1);
                cfg["days"] = step;
                break;
            case "m":
                var y = today.getFullYear(), m = today.getMonth();
                if (m > step - 1) {
                    m = m - step;
                }
                else {
                    y -= 1;
                    m = m + 12 - step;
                }
                var startDate = new Date(y, m, today.getDate());
                cfg["startIndex"] = RTQ_ChartUtil.toDateIndex(startDate);
                
                if (todayIdx - cfg["startIndex"] >= 60) {
                    cfg["freq"] = "d";
                }else{
                    cfg["freq"] = 30;
                }
                break;
            case "y":
                cfg["freq"] = "d";
                var y = today.getFullYear() - step, m = today.getMonth(),d = today.getDate();
                var startDate = new Date(y, m, d);
                cfg["startIndex"] = RTQ_ChartUtil.toDateIndex(startDate);
                break;
            default:
                break;
        }
        
        this.profile.chartCfg = cfg||{};
        this._stateChangeHandler("chartCfg",cfg);
        if(this.miniChart&&this.activeRow){
            var tickerObject = this._getTickerObjectByGkey(this.activeRow.id);
            this._drawMinChart(this.activeRow, tickerObject);
        }
    }
};
